<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2016/9/29
 * Time: 8:37
 */

namespace app\mobile\controller;

class Album extends \think\Controller
{
    private $id;
    public function _initialize()
    {
        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') == false ) {
            die('请在微信端打开');
        }
        parent::_initialize();
        $id = input('param.id');
        $this->id = base64_decode($id);
        $this->assign('id',$id);
        $this->assign('t',time());

    }
    /**
     * @return mixed
     * 空操作 找不到操作方法时执行
     */
    public function _empty(){
        return $this->fetch('public/404');
    }
    //微信 sdk
    private function weixinsdk(){
        vendor('zoujingli.wechat-php-sdk.include');
        $wechat = & \Wechat\Loader::get_instance('Script', $this->getWeixiConfig());
        $sdkconfig = $wechat->getJsSign('http://'.request()->host().$_SERVER['REQUEST_URI']);
        //$jssdk  = new Weixinjssdk($config['appid'], $config['appsecret']);
      //  $sdkconfig = $jssdk->GetSignPackage();
        $this->assign('sdkconfig',json_encode($sdkconfig));
    }
    public function index(){
        $this->weixinsdk();
        $do = input('get.do');
        switch($do){
            case 'edit':
               return $this->edit();
                break;
            default:
               return $this->views();
                break;
        }
    }
    //编辑相册
    public function edit()
    {
        $album = $this->getAlbumInfo();
        $uid = input('param.uid');
        $openid = cookie('wxopenid');
        if ($uid) {
            $userinfo = $this->getUserInfo();
            if ($openid) {
                if ($userinfo['weixin_openid'] == $openid) {
                    $openid = '';
                }
            } else {
                $uri = url('Album/index') . '?do=edit&id=' . base64_encode($this->id) . '&uid=' . $uid;
                $this->getWeixinAuth($uri);
            }
        if ($album) {
            $tpl = $album['tpl'] ? $album['tpl'] : 'style3';
            $music = $album['music'] ? $album['music'] : '/static/weixin/default.mp3';
            $pic = db('weixinalbum_pic')->where(['aid' => $this->id, 'status' => 1])->order('ordid asc')->select();
            $this->tpllist();
            $this->musiclist();
            $this->assign('pics', objToArray($pic));
            $this->assign('dir', $tpl);
            $this->assign('music', $music);
            $this->assign('sharetitle', $userinfo['nickname'] . '的音乐相册-' . $album['title']);
            $this->assign('title', $album['title']);
            $this->assign('img', $album['img']);
            $this->assign('edit', true);
            $this->assign('open', $album['open']);
            $this->assign('openid', $openid);
            $this->assign('uid', $uid);
            $this->assign('site', '');
            $this->view->engine->layout('public/album');
            return $this->fetch('tpl/' . $tpl . '/index');
        }
        }
        return $this->fetch('public/404');
    }
    //分享的相册
    public function views(){
        $album = $this->getAlbumInfo();
        if($album){
            $userinfo = $this->getUserInfo();
            $tpl   = $album['tpl'] ? $album['tpl'] : 'style3';
            $music = $album['music'] ? $album['music'] : '/static/weixin/default.mp3';
            $pic   = db('weixinalbum_pic')->where(['aid'=>$this->id,'status'=>1])->order('ordid asc')->select();
            $this->tpllist();
            $this->musiclist();
            $this->assign('pics',objToArray($pic));
            $this->assign('dir',$tpl);
            $this->assign('music',$music);
            $this->assign('sharetitle', $userinfo['nickname'] . '的音乐相册-' . $album['title']);
            $this->assign('title', $album['title']);
            $this->assign('img',$album['img']);
            $this->assign('open',$album['open']);
            $this->assign('openid','ok');
            $this->assign('uid',$album['uid']);
            $this->assign('site','');
            $this->view->engine->layout('public/album');
            return $this->fetch('tpl/'.$tpl.'/index');
        }
        return $this->fetch('public/404');
    }
    //我的相册列表
    public function myalbum(){
        $this->weixinsdk();
        $uid = input('get.uid',0);
        $openid = cookie('wxopenid');
        if($uid){
            $userinfo = $this->getUserInfo();
            if($openid){
                if($userinfo['weixin_openid']==$openid){
                    $openid = '';
                }
            }else{
                $uri = url('Album/myalbum').'?uid='.$uid;
                $this->getWeixinAuth($uri);
            }
            $lists = db('weixinalbum')->where(['uid'=>$uid,'status'=>1])->select();
            if($lists){
                foreach($lists as &$v){
                    $v['total'] = db('weixinalbum_pic')->where(['aid'=>$v['id'],'status'=>1])->count();
                }
            }
            $this->assign('lists',$lists);
            $this->assign('openid',$openid);
            $this->assign('nickname',$userinfo['nickname']);
            $this->assign('headimg',$userinfo['headimgurl']);
            $this->assign('uid',$uid);
            return $this->fetch();
        }else{
            return $this->fetch('public/404');
        }
    }
    //帮助
    public function help(){
        return $this->fetch();
    }
    /**
     * 更改图片顺序
     */
    public function setPicOrder(){
        $order_str = trim(input('post.order'),',');
        $order = explode(',',$order_str);
        $tmp   = '';
        foreach($order as $k=>$v){
            $tmp[] = sprintf("WHEN %d THEN %d ", $v, $k);
        }
        $edit_str = ' CASE id '.implode(' ',$tmp).' END ';
        //$map['aid'] = $this->id;
       // $map['id'] = ['in',$order_str];
      // $s = db('weixinalbum_pic')->where($map)->setField('ordid',$edit_str)->fetchSql(true);echo $s;
        $sql = 'update fang_weixinalbum_pic set ordid = '.$edit_str.' where aid = '.$this->id.' and id in('.$order_str.')';
        \think\Db::execute($sql);
        return json(1);
    }

    /**
     * 删除相册
     */
    public function delAlbum(){
        $id = input('post.id',0);
        $uid = input('post.uid',0);
        if($id && $uid){
                $map['id'] = $id;
                $map['uid'] = $uid;
                $info = db('weixinalbum')->where($map)->find();
                if($info){
                    $pics = db('weixinalbum_pic')->where(['aid'=>$id])->select();
                    if($pics){
                        foreach($pics as $v){
                            @unlink(str_replace('http://'.config('url_domain_root'),'.',$v['url']));
                        }
                        db('weixinalbum_pic')->where(['aid'=>$id])->delete();
                    }
                    cache($info['openid'],null);
                    db('weixinalbum')->where($map)->delete();
                    return json(['status'=>1,'msg'=>'删除成功']);
                }else{
                    return json(['status'=>0,'msg'=>'删除失败']);
                }
            

        }else{
            return json(['status'=>0,'msg'=>'删除失败']);
        }
    }
    /**
     * 删除图片
     */
    public function delpic(){
        $pid = input('get.pid',0);
        $data['status'] = 0;
        if($pid){
                $album = $this->getAlbumInfo();
                $map['aid'] = $this->id;
                $map['id']  = $pid;
                $pic = db('weixinalbum_pic')->where($map)->find();
                @unlink(str_replace('http://'.config('url_domain_root'),'.',$pic['url']));
                db('weixinalbum_pic')->where($map)->delete();
                if($pic['url'] == $album['img']){
                    $sql = 'update fang_weixinalbum set img = (select url from fang_weixinalbum_pic where aid='.$this->id.' order by ordid asc limit 1) where id='.$this->id;
                    \think\Db::execute($sql);
                }
                $data['status'] = 1;
        }
        
        return json($data);
    }

    /**
     * 添加图片
     */
    public function addpic(){
        $info = model('weixinalbum')->where(['id'=>$this->id])->find();
        if($info){
               cache($info['openid'],$this->id);
            return 1;
        }
        return 0;
    }

    /**
     * @return int
     * 设置相册标题
     */
    public function setTitle(){
        $title = input('post.title','我的相册');
        $open  = input('post.open',0);
        $data['title'] = $title;
        $data['open']  = $open;
        $map['id'] = $this->id;
        db('weixinalbum')->where($map)->update($data);
        return 1;
    }
    /**
     * @return \think\response\Json
     * 设置模板
     */
    public function setTpl(){
        $sid = input('post.sid',0);
        $uid = input('get.uid',0);
        $data['status'] = 0;
        $data['msg']    = '参数错误';
        if($sid){
            $tpl = db('weialbum')->where(['id'=>$sid])->value('tpl');
            if(db('weixinalbum')->where(['id'=>$this->id,'uid'=>$uid])->update(['tpl'=>$tpl])){
                $data['status'] = 1;
                $data['url']     = url('Album/index').'?do=edit&uid='.$uid.'&id='.input('param.id').'&t='.time();
            }
        }
        return json($data);
    }

    /**
     * @return \think\response\Json
     * 设置音乐
     */
    public function setMusic(){
        $sid = input('post.mid',0);
        $data['status'] = 0;
        $data['msg']    = '参数错误';
        if($sid){
            db('weixinalbum')->where(['id'=>$this->id])->update(['music'=>$sid]);
                $data['status'] = 1;
                $data['url']     = url('Album/index').'?do=edit&id='.input('param.id');
            }
        return json($data);
    }
    /**
     * 模板列表
     */
    private function tpllist(){
        $tplcate = db('linkmenu')->where(['menuid'=>3])->order('ordid asc,id asc')->select();
        $list    = db('weialbum')->where(['status'=>1])->order('id desc')->select();
        $tpl_hot_arr = [];$tpl_arr = [];
        if($list){
            foreach($list as $v){
                if($v['hot'] == 1){
                    $tpl_hot_arr[] = $v;
                }
                    $tpl_arr[$v['cate_id']][] = $v;

            }
        }
        $this->assign('tplhot',$tpl_hot_arr);
        $this->assign('tpllists',$tpl_arr);
        $this->assign('tplcate',$tplcate);
    }
    /**
     * 音乐列表
     */
    private function musiclist(){
        $tplcate = db('linkmenu')->where(['menuid'=>4])->order('ordid asc,id asc')->select();
        $list    = db('weimusic')->where(['status'=>1])->order('id desc')->select();
        $hot_arr = [];$music_arr = [];
        if($list){
            foreach($list as $v){
                if($v['hot'] == 1){
                    $hot_arr[] = $v;
                }
                    $music_arr[$v['cate_id']][] = $v;

            }
        }
        $this->assign('musichot',$hot_arr);
        $this->assign('lists',$music_arr);
        $this->assign('musiccate',$tplcate);

    }
    /**
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     * 获取相册详细
     */
    private function getAlbumInfo(){
        $album = db('weixinalbum')->where(['id'=>$this->id,'status'=>1])->find();
        if(!$album){
            die('缺少参数');
        }
        if($album['music']){
            $album['music'] = db('weimusic')->where(['id'=>$album['music']])->value('url');
        }
        return $album;
    }
    private function getWeixiConfig(){

            return getWeixinConfig();


    }
    //获取用户信息
    private function getUserInfo(){
        $uid = input('param.uid');
        if($uid){
            $info = db('user')->where(['id'=>$uid])->field('id,c_id,nickname,headimgurl,weixin_openid')->find();
            if(!$info){
                die('参数错误');
            }else{
                return $info;
            }
        }else{
            die('参数错误');
        }
    }
    private function getWeixinAuth($uri=''){
        $info = $this->getUserInfo();
        $url = 'http://'.config('url_domain_root').'/weixin/getoauth/id/'.\org\Crypt::encrypt($info['id']).'.html';
        $obj = controller('manage/Weixin','event');
        $obj->init('Oauth');
        $url = $obj->getAuthUrl($url,base64_encode($uri));
        $this->redirect($url);
    }
}